var prefix = jsctx + "/enterpriseMember";

var enterpriseMember = (function () {
    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    };

    function init() {
        setTimeout(function () {//防止先于-读取缓存执行
            load();
        }, 10)
    };
    var h = $(window).height() - 40;

    function load() {
        $('#exampleTable')
            .bootstrapTable({
                method: 'get',
                url: prefix + "/listEnterpriseMember",
                iconSize: 'outline',
                toolbar: '#exampleToolbar',
                striped: false,
                dataType: "json",
                pagination: true,
                singleSelect: false,
                pageList: [10, 20, 30],
                pageSize: 10,
                pageNumber: 1,
                sidePagination: "server",
                cache: false,
                height: h,
                paginationShowPageGo: true,
                // rightFixedColumns: true,
                showColumns: true,
                queryParams: function (params) {
                    return {
                        limit: params.limit,
                        offset: (params.offset / params.limit) + 1,
                        mobile: $("#mobile").val().trim(),
                        enterpriseType: $("#enterpriseType").val(),
                        enterpriseName: $("#enterpriseName").val().trim(),
                        nickname: $("#nickname").val().trim()
                    };
                },
                columns: [
                    {
                        field: 'number',
                        title: '序号',
                        width: '50', align: 'center',
                        formatter: function (value, row, index) {
                            return index + 1;
                        }
                    },
                    {field: 'tenantCode', title: '运营商', align: 'left', width: '100'},
                    {
                        field: 'enterpriseType',
                        title: '企业会员类型',
                        width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (row.enterpriseType == '0') {
                                return '普通企业会员';
                            } else if (row.enterpriseType == '1') {
                                return '商户企业会员';
                            }
                        }
                    },
                    {field: 'nickname', title: '昵称', align: 'left', width: '100'},
                    {field: 'memberRemark', title: '备注', align: 'left', width: '100'},
                    {field: 'mobile', title: '手机号', align: 'left', width: '100'},
                    {field: 'enterpriseName', title: '公司名称', align: 'left', width: '100'},
                    {field: 'address', title: '详细地址', align: 'left', width: '100'},
                    {field: 'account', title: '个人余额', align: 'left', width: '100'},
                    {field: 'enterpriseAccount', title: '企业余额', align: 'left', width: '100'},
                    {field: 'auditTime', title: '注册时间', align: 'left', width: '100'},
                    {
                        field: 'status',
                        title: '状态',
                        width: '100', align: 'left',
                        formatter: function (value, row, index) {
                            if (row.status == '0') {
                                return '<span class="label label-success">正常</span>';
                            } else if (row.status == '1') {
                                return '<span class="label label-danger">停用</span>';
                            }
                        }
                    },
                    {
                        title: '操作',
                        field: 'orderId',
                        width: '400', align: 'center',
                        formatter: function (value, row, index) {
                            var a = '';
                            var b = '';
                            var c = '';
                            var d = '';
                            var e = '';
                            var f = '';
                            var g = '';
                            var h = '';
                            // var i = '';
                            // var j = '';

                            if (MemberManager_enterpriseMember_add) {
                                a = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="新增子会员" onclick="enterpriseMember.addEnterpriseSubmember(\''
                                    + row.enterpriseId + '\')">新增子会员</a> ';
                            }
                            if (MemberManager_enterpriseMember_update) {
                                b = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" mce_href="#" title="子会员" onclick="enterpriseMember.enterpriseSubmember(\''
                                    + row.enterpriseId + '\')">子会员</a> ';
                                d = '<a class="btn btn-warning btn-sm ' + has_edit + '" href="#" mce_href="#" title="子会员注销列表" onclick="enterpriseMember.cancel(\''
                                    + row.enterpriseId + '\')">子会员注销列表</a> ';
                                e = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="共享余额" onclick="enterpriseMember.addEnterpriseShare(\''
                                    + row.enterpriseId + '\')">共享余额</a> ';
                                f = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="企业会员折扣" onclick="enterpriseMember.enterpriseDiscount(\''
                                    + row.enterpriseId + '\')">企业会员折扣</a> ';
                                g = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="余额" onclick="enterpriseMember.subMemberAmountRecord(\''
                                    + row.memberId + '\')">余额</a> ';
                                h = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="重置密码" onclick="enterpriseMember.updateEnterprisePassword(\''
                                    + row.memberId + '\')">重置密码</a> ';
                                // if (row.status == '0') {
                                //     i = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" mce_href="#" title="冻结" onclick="enterpriseMember.updateEnterpriseMemberStatus(\''
                                //         + row.memberId + '\')">冻结</a> ';
                                // } else if (row.status == '1') {
                                //     j = '<a class="btn btn-success btn-sm ' + has_edit + '" href="#" mce_href="#" title="解冻" onclick="enterpriseMember.updateEnterpriseMemberStatus(\''
                                //         + row.memberId + '\')">解冻</a> ';
                                // }
                            }
                            if (MemberManager_enterpriseMember_look) {
                                c = '<a class="btn btn-primary btn-sm ' + has_edit + '" href="#" mce_href="#" title="订单列表" onclick="enterpriseMember.enterpriseOrder(\''
                                    + row.enterpriseId + '\')">订单列表</a> ';
                            }
                            // if (row.status == '0') {
                            //     return a + b + c + d + e + f + g + h + i ;
                            // } else if (row.status == '1') {
                            //     return a + b + c + d + e + f + g + h + j ;
                            // }
                            return a + b + c + d + e + f + g + h;
                        }
                    }
                ]
            });
    };

    function enterpriseDiscount(enterpriseId) {
        location.href = prefix + "/enterpriseDiscount/" + enterpriseId;
    }

    function addEnterpriseSubmember(enterpriseId) {
        location.href = prefix + "/addEnterpriseSubmember/" + enterpriseId;
    }

    function enterpriseSubmember(enterpriseId) {
        location.href = prefix + "/enterpriseSubmember/" + enterpriseId;
    }

    function enterpriseOrder(enterpriseId) {
        location.href = prefix + "/enterpriseOrder/" + enterpriseId;
    }

    function cancel(enterpriseId) {
        location.href = prefix + "/cancel/" + enterpriseId;
    }

    function addEnterpriseShare(enterpriseId) {
        location.href = prefix + "/addEnterpriseShare/" + enterpriseId;
    }

    function subMemberAmountRecord(memberId) {
        location.href = prefix + "/subMemberAmountRecord/" + memberId;
    }

    function exportEnterpriseMember() {
        $.fileDownload(prefix + "/exportEnterpriseMember", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                mobile: $("#mobile").val().trim(),
                count: $("#count").val().trim() == '' ? 0 : $("#count").val().trim(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }


    function resetPassword(memberId) {
        layer.confirm('确定要重置密码？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/resetPassword",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("重置成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function updateEnterprisePassword(memberId) {
//  $("#recipient-name").val(sort)
        //  $("#ulId").val(ulId)
        $('#exampleModal').modal('show')

        $("#updateEnterprisePassword").unbind("click").bind("click", function () {

            var formData = new FormData();
            formData.append("password", $("#password").val());
            formData.append("verifyPassword", $("#verifyPassword").val());
            formData.append("memberId", memberId);
            $.ajax({
                url: prefix + "/updateEnterprisePassword",
                type: "post",
                data: formData,
                dataType: "json",
                processData: false, // 告诉jQuery不要去处理发送的数据，用于对data参数进行序列化处理 这里必须false
                contentType: false, // 告诉jQuery不要去设置Content-Type请求头
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        $('#exampleModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#exampleModal').on('hidden.bs.modal', function () {
                            document.getElementById("contentForm").reset();
                        })
                        //  $('#exampleModal').modal('hide')
                    }

                }
            })
        })

    }

    function updateEnterpriseMemberStatus(memberId) {
        layer.confirm('确定要变更状态？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/updateEnterpriseMemberStatus",
                type: "post",
                data: {
                    'memberId': memberId
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("变更成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }

    return {
        init: init,
        reLoad: reLoad,
        addEnterpriseSubmember: addEnterpriseSubmember,
        enterpriseSubmember: enterpriseSubmember,
        enterpriseOrder: enterpriseOrder,
        cancel: cancel,
        addEnterpriseShare: addEnterpriseShare,
        enterpriseDiscount: enterpriseDiscount,
        subMemberAmountRecord: subMemberAmountRecord,
        exportEnterpriseMember: exportEnterpriseMember,
        resetPassword: resetPassword,
        updateEnterprisePassword: updateEnterprisePassword,
        updateEnterpriseMemberStatus: updateEnterpriseMemberStatus
    };
})();

var addEnterPriseMember = (function () {
        function init() {
            validateRule();
        };

        var isajaxsend = true;

        function save() {
            if (isajaxsend) {
                $.ajax({
                    cache: true,
                    type: "POST",
                    url: prefix + "/saveEnterpriseSubmember",
                    data: $('#frmEnterpriseSubmember').serialize(),
                    async: false,
                    beforeSend: function () {
                        isajaxsend = false
                    },
                    error: function (request) {
                        parent.layer.alert("请重新登录");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            isajaxsend = false
                            parent.layer.alert(data.message)
                            javascript:history.back(-1);
                        } else if (data.status == 201) {
                            isajaxsend = true;
                            parent.layer.alert(data.message)
                        } else {
                            isajaxsend = true;
                            parent.layer.alert(data.message);
                        }
                    },

                });
            }
            ;
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmEnterpriseSubmember").validate({
                rules: {
                    enterpriseName: {
                        required: true,
                        maxlength: 25,
                    },
                    license: {
                        required: true,
                        maxlength: 18
                    },
                    taxPayerCode: {
                        required: true,
                        maxlength: 18
                    },
                    enterpriseBank: {
                        required: true
                    },
                    enterpriseBankAccount: {
                        required: true
                    },
                    enterpriseOwner: {
                        required: true
                    },
                    ownerMobile: {
                        required: true
                    }
                },
                messages: {
                    enterpriseName: {
                        required: icon + "请输入",
                        maxlength: icon + "不能超过25位"
                    },
                    license: {
                        required: icon + "请输入",
                        maxlength: icon + "不能超过18位"
                    },
                    taxPayerCode: {
                        required: icon + "请输入",
                        maxlength: icon + "不能超过18位"
                    },
                    enterpriseBank: {
                        required: icon + "请输入"
                    },
                    enterpriseBankAccount: {
                        required: icon + "请输入"
                    },
                    enterpriseOwner: {
                        required: icon + "请输入"
                    },
                    ownerMobile: {
                        required: icon + "请输入"
                    }
                },
                submitHandler: function (form) {
                    save();
                }
            })
        };

        /*------  验证码  -----*/
        var num1 = 60;
        var ajaxReady = true;

        function getAuthCode() {
            if (ajaxReady) {
                $.ajax({
                    url: prefix + "/getReviewAuthCode",
                    type: "POST",
                    data: {mobile: $("#mobile").val()},
                    beforeSend: function () {
                        ajaxReady = false;
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            time();

                            function time() {
                                if (num1 == 0) {
                                    $('#verificationCode').attr("disabled", "disabled")
                                    $('#sendVerificationCode').text("获取验证码");
                                    $('#sendVerificationCode').attr("onclick", 'addEnterPriseMember.getAuthCode()');
                                    ajaxReady = true;
                                    num1 = 60;
                                } else {
                                    $('#verificationCode').removeAttr('disabled')
                                    $('#sendVerificationCode').html(num1 + "秒后重试");
                                    $('#sendVerificationCode').removeAttr('onclick');
                                    num1--;
                                    setTimeout(function () {
                                        time()
                                    }, 1000)
                                }
                            }
                        } else {
                            parent.layer.alert(data.message);
                            $('#verificationCode').removeAttr('disabled')
                            $('#sendVerificationCode').text("获取验证码");
                            $('#sendVerificationCode').attr("onclick", 'addEnterPriseMember.getAuthCode()');
                            ajaxReady = true;
                            num1 = 60;
                        }

                    }
                })


            }
        };


        return {
            init: init,
            getAuthCode: getAuthCode
        };

    }
)();


var addEnterpriseShare = (function () {
        function init() {
            validateRule();
        };

        var isajaxsend = true;

        function save() {
            if (isajaxsend) {
                $.ajax({
                    cache: true,
                    type: "POST",
                    url: prefix + "/saveEnterpriseShare",
                    data: $('#frmEnterpriseShare').serialize(),
                    async: false,
                    beforeSend: function () {
                        isajaxsend = false
                    },
                    error: function (request) {
                        parent.layer.alert("请重新登录");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            parent.layer.msg("保存成功");
                            javascript:history.back(-1);
                        } else {
                            parent.layer.alert(data.message);
                        }
                    },
                    complete: function () {
                        isajaxsend = false
                    }

                });
            }
            ;
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmEnterpriseShare").validate({
                rules: {
                    status: {
                        required: true
                    },
                    beginTime: {
                        required: true
                    },
                    endTime: {
                        required: true
                    },
                    fixedPower: {
                        required: true,
                        number: true,
                        min: 0
                    },
                    shareType: {
                        required: true
                    },
                    fixedAccount: {
                        required: true,
                        number: true,
                        min: 0
                    }
                },
                messages: {
                    status: {
                        required: icon + "请选择是否启用共享余额"
                    },
                    beginTime: {
                        required: icon + "请选择开始时间"
                    },
                    endTime: {
                        required: icon + "请选择结束时间"
                    },
                    fixedPower: {
                        required: icon + "请输入充电量限额",
                        number: icon + "请输入大于0的数",
                        min: icon + "请输入大于0的整数"
                    },
                    shareType: {
                        required: icon + "请选择授权类型"
                    },
                    fixedAccount: {
                        required: icon + "请输入授权金额",
                        number: icon + "请输入大于0的数",
                        min: icon + "请输入大于0的整数"
                    }
                },
                errorPlacement: function (error, element) {
                    element.after(error);
                },
                submitHandler: function (form) {
                    save();
                }
            })
        };


        return {
            init: init
        };

    }
)();


var addSubmemberShare = (function () {
        function init() {
            validateRule();
        };

        var isajaxsend = true;

        function save() {
            if (isajaxsend) {
                $.ajax({
                    cache: true,
                    type: "POST",
                    url: prefix + "/saveSubmemberShare",
                    data: $('#frmSubmemberShare').serialize(),
                    async: false,
                    beforeSend: function () {
                        isajaxsend = false
                    },
                    error: function (request) {
                        parent.layer.alert("请重新登录");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            parent.layer.msg("保存成功");
                            javascript:history.back(-1);
                        } else {
                            parent.layer.alert(data.message);
                        }
                    },
                    complete: function () {
                        isajaxsend = false
                    }

                });
            }
            ;
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmSubmemberShare").validate({
                rules: {
                    status: {
                        required: true
                    },
                    beginTime: {
                        required: true
                    },
                    endTime: {
                        required: true
                    },
                    fixedPower: {
                        required: true,
                        number: true,
                        min: 0
                    },
                    shareType: {
                        required: true
                    },
                    fixedAccount: {
                        required: true,
                        number: true,
                        min: 0
                    }
                },
                messages: {
                    status: {
                        required: icon + "请选择是否启用共享余额"
                    },
                    beginTime: {
                        required: icon + "请选择开始时间"
                    },
                    endTime: {
                        required: icon + "请选择结束时间"
                    },
                    fixedPower: {
                        required: icon + "请输入充电量限额",
                        number: icon + "请输入大于0的数",
                        min: icon + "请输入大于0的数"
                    },
                    shareType: {
                        required: icon + "请选择授权类型"
                    },
                    fixedAccount: {
                        required: icon + "请输入授权金额",
                        number: icon + "请输入大于0的数",
                        min: icon + "请输入大于0的数"
                    }
                },
                submitHandler: function (form) {
                    save();
                }
            })
        };


        return {
            init: init
        };

    }
)();


var editEnterpriseAmount = (function () {

        /*------  验证码  -----*/
        var num1 = 60;
        var ajaxReady = true;

        function getAuthCode() {
            if (ajaxReady) {
                $.ajax({
                    url: prefix + "/getEnterpriseAmountAuthCode",
                    type: "POST",
                    data: {},
                    beforeSend: function () {
                        ajaxReady = false;
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            time();

                            function time() {
                                if (num1 == 0) {
                                    $('#verificationCode').attr("disabled", "disabled")
                                    $('#sendVerificationCode').text("获取验证码");
                                    $('#sendVerificationCode').attr("onclick", 'editEnterpriseAmount.getAuthCode()');
                                    ajaxReady = true;
                                    num1 = 60;
                                } else {
                                    $('#verificationCode').removeAttr('disabled')
                                    $('#sendVerificationCode').html(num1 + "秒后重试");
                                    $('#sendVerificationCode').removeAttr('onclick');
                                    num1--;
                                    setTimeout(function () {
                                        time()
                                    }, 1000)
                                }
                            }
                        }

                    }
                })


            }
        };


        function init() {
            validateRule();
        };

        var isajaxsend = true;

        function save() {
            if (isajaxsend) {
                $.ajax({
                    cache: true,
                    type: "POST",
                    url: prefix + "/saveEnterpriseAmount",
                    data: $('#frmEnterpriseAmount').serialize(),
                    async: false,
                    beforeSend: function () {
                        isajaxsend = false
                    },
                    error: function (request) {
                        parent.layer.alert("请重新登录");
                    },
                    success: function (data) {
                        if (data.status == 200) {
                            parent.layer.msg("保存成功");
                            javascript:history.back(-1);
                        } else {
                            parent.layer.alert(data.message);
                        }
                    },
                    complete: function () {
                        isajaxsend = false
                    }

                });
            }
            ;
        }

        function validateRule() {
            var icon = "<i class='fa fa-times-circle'></i> ";
            $("#frmEnterpriseAmount").validate({
                rules: {
                    status: {
                        required: true
                    }
                },
                messages: {
                    status: {
                        required: icon + "请选择是否启用共享余额"
                    }
                },
                submitHandler: function (form) {
                    save();
                }
            })
        };


        return {
            init: init,
            getAuthCode: getAuthCode
        };

    }
)();

var editEnterprise = (function () {
    function init() {

        validateRule();
    };

    function save() {
        var formData = new FormData($("#frmEnterprise")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/updateEnterprise",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("请重新登录");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    javascript:history.back(-1);
                } else {
                    if (data.status == 600) {
                        javascript:history.back(-1);
                    } else {
                        parent.layer.alert(data.message);
                    }
                }
            }
        });
    };

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frmEnterprise").validate({
            rules: {
                enterpriseName: {
                    required: true,
                    maxlength: 25,
                },
                license: {
                    required: true,
                    maxlength: 18
                },
                taxPayerCode: {
                    required: true,
                    maxlength: 18
                },
                enterpriseBank: {
                    required: true
                },
                enterpriseBankAccount: {
                    required: true
                },
                enterpriseOwner: {
                    required: true
                },
                ownerMobile: {
                    required: true
                }
            },
            messages: {
                enterpriseName: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过25位"
                },
                license: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                taxPayerCode: {
                    required: icon + "请输入",
                    maxlength: icon + "不能超过18位"
                },
                enterpriseBank: {
                    required: icon + "请输入"
                },
                enterpriseBankAccount: {
                    required: icon + "请输入"
                },
                enterpriseOwner: {
                    required: icon + "请输入"
                },
                ownerMobile: {
                    required: icon + "请输入"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    };
    return {
        init: init
    };


})();